package com.wtwd.device.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.device.annotation.PaidService;
import com.wtwd.device.model.GFWeather;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;


/**
 * @author zdl
 * @Description
 * @create 2021-08-17 11:42
 */
@Component
public class GFWeatherUtil {
    public static final String BASE_URL = "http://gfapi.mlogcn.com/weather/v001/day";

    public static final String CITY_URL = "http://gfapi.mlogcn.com/function/v001/poi";

    public static final String GF_KEY = "2xHnJlTR3XiFl3BR6cWR57AEwng0eGFL";

    private static final Logger log = LoggerFactory.getLogger(GFWeatherUtil.class);

    @PaidService(serviceName = "w")
    public GFWeather getWeather(String cid, String language) {
        if (StringUtils.isEmpty(cid)) {
            return null;
        }
        String params = "key=" + GF_KEY + "&areacode=" + cid + "&lang=" + language + "&days=3";
        String response = HttpClients.getForObject(BASE_URL + "?" + params);
        log.info("获取天气:{},{}",cid,response);
        GFWeather heWeather = transToGFWeather(response);
        return heWeather;
    }

    private  GFWeather transToGFWeather(String response) {
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject == null || jsonObject.getIntValue("status") != 0) {
            return null;
        }
        GFWeather weather = jsonObject.getObject("result", GFWeather.class);
        if (weather == null) {
            return null;
        }
        jsonObject.getObject("daily_fcsts", ArrayList.class);
        weather.setWeatherInfoList(JSON.parseArray(jsonObject.getJSONObject("result").getString("daily_fcsts"), GFWeather.WeatherInfo.class));
        return weather;
    }

    @PaidService(serviceName = "w")
    public  GFWeather.Location getCityData(String lon, String lat, String lang) {
        String params = "key=" + GF_KEY + "&lonlat=" + lon + "," + lat + "&language=" + lang;
        String response = HttpClients.getForObject(CITY_URL + "?" + params);
        log.info("获取城市:{}", response);
        GFWeather.Location location = transToCityData(response); //JSON.parseObject(response,HeWeather.class);
        return location;
    }

    private  GFWeather.Location transToCityData(String response) {
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject == null || jsonObject.getIntValue("status") != 0) {
            return null;
        }
        return jsonObject.getObject("location", GFWeather.Location.class);
    }
}
